$(function () {
    var styleNode = createLink("./font.css");
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var screenW = window.screen.width;
    var screenH = window.screen.height;
    // 画布文字x, y 坐标系数
    var textXRate = 0.12;
    var textYRate = 0.3;
    if (screenH > 780) {
        textYRate = 0.365
    }
    $('.swiper-slide').height(windowHeight)
    var moveH = screenH - windowHeight;

    // rem适配
    var htmlFont = $(window).width() / 7.5 + 'px'
    document.documentElement.style.fontSize = htmlFont;
    var mySwiper = new Swiper('.swiper-container', {
        autoplay: false,
        // watchSlidesProgress: true, // 监听滑动进度
        // watchSlidesVisibility: true,
        preventLinksPropagation: true, // 滑动防止穿透
        allowTouchMove: false, // 不允许手动滑动
        on: {
            // 当一个页面结束后,才开始动画
            slideChangeTransitionEnd: function () {
                $(".wave_bg").addClass("waverun");
                $('.ladle').addClass('ladlerun')
            },
            // 向下一个页面滑动结束后,才开始动画
            slideNextTransitionEnd: function () {
                // alert('切换结束了');
            },
        },
    })

    // 第一页
    $('.start_game').on('click', function (e) {
        $(".index_btn img").addClass("btn_animate");
        setTimeout(function () {
            mySwiper.slideTo(1);
            $(".index_btn img").removeClass("btn_animate");
        }, 300)
    })

    // 第二页
    var nickVal = $('.nickname_input').val();
    // 输入姓名
    var inputObj = $(".nickname_input").get(0);
    $('.nickname_input').on('input', function () {
        // 阻止ios点击input页面顶起
        inputObj.scrollIntoView(false);
        // 限制input输入长度
        var $that = $(this),
            limitLen = 12; //定义所需字节数
        $that.attr('maxlength', limitLen);
        setTimeout(function () {
            var value = $that.val(),
                reg = /[\u4e00-\u9fa5]{1}/g, //中文
                notReg = /\w{1}/g; //非中文
            var resultCn = value.match(reg);
            var resultEn = value.match(notReg);
            if (resultCn) {
                limitLen = limitLen - (resultCn.length * 2);
            }
            if (resultEn) {

                limitLen = limitLen - resultEn.length;
            }
            if (limitLen <= 0) {
                var finalLen = value.length + limitLen;
                value = value.substring(0, finalLen);
                $that.attr('maxlength', limitLen);
                $that[0].value = value;
            }
        }, 0);

        nickVal = $(this).val().trim();
        $('.tips').hide();
    }).blur(function () {

        nickVal = $(this).val().trim();
 
        if (nickVal == '') {
            $('.tips').fadeIn();
        }

        // 第三页img 生成功能
        // 第三页 canvas  图片-文字合成
        var imgArr = [
            "./images/gg01.jpg",
            "./images/gg02.jpg",
            "./images/gg03.jpg",
            "./images/gg04.jpg",
            "./images/gg05.jpg",
            "./images/gg06.jpg"
        ];
        var xximgArr = [
            "./images/xx01.jpg",
            "./images/xx02.jpg",
            "./images/xx03.jpg",
            "./images/xx04.jpg",
            "./images/xx05.jpg",
            "./images/xx06.jpg"
        ]
        var randomNum = Math.floor(Math.random() * imgArr.length);
        var imgSrc = imgArr[randomNum];

        if (screenH > 780) {
            imgSrc = xximgArr[randomNum]
        }

        $("#imgcanvas").attr('width', screenW * 2);
        $("#imgcanvas").attr('height', screenH * 2);
        $("#imgcanvas").width(screenW)
        $("#imgcanvas").height(screenH)
        var can = document.getElementById("imgcanvas");
        var ctx = can.getContext("2d");
        var nickname = can.getContext("2d");
        var img = new Image();

        img.src = imgSrc;
        if (nickVal == "") {
            nickVal = "哈哈哈"
        }
        styleOnload(styleNode, function () {
            img.onload = function () {
                ctx.drawImage(img, 0, 0, windowWidth * 2, screenH * 2);
                // ctx.font = "small-caps bold 30px Suxin";
                // ctx.fillText(nickVal, 80, 400);

                nickname.font = "normal normal bold 48px 'Suxin'";
                nickname.fillStyle = "#f7493f";
                nickname.translate(textXRate * windowWidth, textYRate * screenH);
                nickname.rotate(-Math.PI / 45);
                nickname.fillText(nickVal, textXRate * windowWidth, textYRate * screenH);

                var dataURL = can.toDataURL("image/png");
                $('.posters_img').attr('src', dataURL);
            };
        });
        $(".posters_img").css({
            width: windowWidth + "px",
            height: screenH + "px",
            "transform": "translateY(-" + moveH + "px)"
        })
    }).on("click", function () {
        inputObj.scrollIntoView(false);
    })
    // 选择性别
    var sexList = $(".select_sex").find(".select_gender");
    sexList.each(function (i, v) {
        $(this).on('click', function () {
            $('.tips').fadeOut();
            sexList.each(function (i, v) {
                $(v).removeAttr("checked");
            })
            $(this).attr("checked", 'true')
            // $(v).removeProp()
        })

    })
    // 选择日期
    $('#datePicker').on('click', function () {
        $('.tips').fadeOut();
        // $(this).attr("disabled", 'true');
        weui.datePicker({
            start: 1930,
            end: new Date(),
            defaultValue: [1995, 6, 9],
            onChange: function (result) {},
            onConfirm: function (result) {
                console.log(result)
                var year = result[0] + '';
                var month = result[1].value < 10 ? "0" + result[1].value : result[1].value;
                var day = result[2].value < 10 ? "0" + result[2].value : result[2].value;
                result[1].value = month;
                result[2].value = day;
                // var dateResult = year + '-' + month + '-' + day;
                // var dateResult = result + '';
                // dateResult = dateResult.replace(new RegExp(",", "g"), '-');
                $(".year").html(year);
                $(".month").html(month);
                $(".day").html(day);
            },
            id: 'datePicker'
        });
    })
    // 点击生成
    $('.next_slider2').on('click', function (e) {
        // 判断昵称输入
        nickVal = $('.nickname_input').val().trim();
        // 判断性别选择
        var sexCheckedArr = [];
        // 判断日期选择
        var dateVal = $('#datePicker .year').html();
        sexList.each(function (i, v) {
            if ($(this).attr("checked")) {
                sexCheckedArr.push($(this).val())
            }
        })
        if (nickVal != '' && sexCheckedArr.length && dateVal != '') {
            mySwiper.slideTo(2);
        } else {
            $('.tips').fadeIn();
        }
    })

    // function loadcss() {
    //     styleOnload(styleNode, function () {
    //         alert("嗡嗡嗡")
    //     });
    // }
    // 判断 自定义字体 加载状态 开始-----------------------
    function styleOnload(node, callback) {
        // for IE6-9 and Opera
        if (node.attachEvent) {
            node.attachEvent("onload", callback);
            // NOTICE:
            // 1. "onload" will be fired in IE6-9 when the file is 404, but in
            // this situation, Opera does nothing, so fallback to timeout.
            // 2. "onerror" doesn't fire in any browsers!
        }
        // polling for Firefox, Chrome, Safari
        else {
            setTimeout(function () {
                poll(node, callback);
            }, 0); // for cache
        }
    }

    function poll(node, callback) {
        if (callback.isCalled) {
            return;
        }
        var isLoaded = false;
        if (/webkit/i.test(navigator.userAgent)) {
            //webkit
            if (node["sheet"]) {
                isLoaded = true;
            }
        }
        // for Firefox
        else if (node["sheet"]) {
            try {
                if (node["sheet"].cssRules) {
                    isLoaded = true;
                }
            } catch (ex) {
                // NS_ERROR_DOM_SECURITY_ERR
                if (ex.code === 1000) {
                    isLoaded = true;
                }
            }
        }
        if (isLoaded) {
            // give time to render.
            setTimeout(function () {
                callback();
            }, 1);
        } else {
            setTimeout(function () {
                poll(node, callback);
            }, 1);
        }
    }
    // 我的动态创建LINK函数
    function createLink(cssURL, lnkId, charset, media) {
        var head = document.getElementsByTagName("head")[0],
            linkTag = null;
        if (!cssURL) {
            return false;
        }
        linkTag = document.createElement("link");
        linkTag.setAttribute("id", lnkId || "dynamic-style");
        linkTag.setAttribute("rel", "stylesheet");
        linkTag.setAttribute("charset", charset || "utf-8");
        linkTag.setAttribute("media", media || "all");
        linkTag.setAttribute("type", "text/css");
        linkTag.href = cssURL;
        head.appendChild(linkTag);
        return linkTag;
    }
    // 判断 自定义字体 加载状态 结束 -----------------------

    
    // 第四页
    // var selectItem = $('.select_list').find('.select_item');
    // selectItem.each(function (i, v) {
    //     $(this).on('click', function () {
    //         selectItem.each(function (i, v) {
    //             $(v).removeAttr("checked");
    //         })
    //         $(this).attr("checked", 'true')
    //         // $(v).removeProp()
    //     })
    // });
    // $('.next_slider3').on('click', function () {
    //     var checkedArr = [];
    //     selectItem.each(function (i, v) {
    //         if ($(v).attr('checked')) {
    //             checkedArr.push($(v).val());
    //         }
    //         // if($(v).attr('checked')){
    //         //     mySwiper.slideTo(3);
    //         // }else {
    //         //     console.log("请选择一个选项")
    //         // }
    //     })
    //     if (checkedArr.length) {
    //         mySwiper.slideTo(3);
    //     } else {
    //         console.log("请选择选项")
    //     }

    // })


})